package org.ioriframework.boot.job.config;

import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.ioriframework.boot.core.rest.VirtualTokenInterceptor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.client.RestTemplate;

/**
 * Job相关配置
 * 
 * @author iori
 *
 */
@Configuration
public class JobConfig {

	@Value("${job.rest.readTimeout}")
	private int readTimeout;

	@Value("${job.rest.connectTimeout}")
	private int connectionTimeout;

	@Bean("jobHttpClientFactory")
	public SimpleClientHttpRequestFactory jobHttpClientFactory() {
		SimpleClientHttpRequestFactory jobHttpClientFactory = new SimpleClientHttpRequestFactory();
		jobHttpClientFactory.setReadTimeout(readTimeout);
		jobHttpClientFactory.setConnectTimeout(connectionTimeout);
		return jobHttpClientFactory;
	}

	@Bean("jobRestTemplate")
	public RestTemplate jobRestTemplate(@Qualifier("jobHttpClientFactory")SimpleClientHttpRequestFactory jobHttpClientFactory) {
		RestTemplate jobRestTemplate = new RestTemplate(jobHttpClientFactory);
		// 使用utf-8编码集的StringHttpMessageConverter替换默认的StringHttpMessageConverter默认的编码集为"ISO-8859-1"）
        List<HttpMessageConverter<?>> messageConverters = jobRestTemplate.getMessageConverters();
        Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
        while (iterator.hasNext()) {
            HttpMessageConverter<?> converter = iterator.next();
            if (converter instanceof StringHttpMessageConverter) {
                iterator.remove();
            }
        }
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        // 配置虚拟令牌拦截器
		jobRestTemplate.setInterceptors(Collections.singletonList(new VirtualTokenInterceptor()));
		return jobRestTemplate;
	}

	@Bean(name = "schedulerFactory")
	public SchedulerFactoryBean schedulerFactory() {
		SchedulerFactoryBean bean = new SchedulerFactoryBean();
		// 用于quartz集群,QuartzScheduler 启动时更新己存在的Job
		// bean.setOverwriteExistingJobs(true);
		// 延时启动，应用启动1秒后
		// bean.setStartupDelay(1);
		return bean;
	}
}
